package servlets;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.UserDAO;
import model.entity.User;
import servlets.util.ParamUtil;
import util.CookieUtil;
import util.EncryptUtil;
import exceptions.ParameterNotFoundException;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<String> paramNames = Arrays.asList("user_mail", "user_password");
		Map<String, String> params = new HashMap<String, String>();
		try {
			params = ParamUtil.getValues(request, paramNames);
		} catch (ParameterNotFoundException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		UserDAO dao = new UserDAO(User.class);
		User u = null;
		u = dao.findByMail(params.get("user_mail"));
		if (u == null) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		// Verifica password
		if (!EncryptUtil.verifyPassowrd(params.get("user_password"),
				u.getPassword())) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
		// tudo ok
		response.addCookie(CookieUtil.makeCookie(u.getMail(), u.getSalt()));
		response.setStatus(HttpServletResponse.SC_OK);
	}

}
